<template>
  <el-row v-if="isFormInit" :gutter="12" class="base-search">
    <el-col
      v-for="(item, index) in formList"
      :key="index"
      :xs="xs"
      :sm="sm"
      :md='md'
      :lg='lg'
      :xl='xl'
      :xxl='xxl'>
      
        <!-- text -->
        <el-input
          v-if="item.type === FORM_TYPE_TEXT"
          v-model="formData[item.prop]"
          :size="formSize"
          :placeholder="item.label" />

        <!-- select -->
        <el-select
          v-else-if="item.type === FORM_TYPE_SELECT"
          v-model="formData[item.prop]"
          :clearable="((item.clearable ?? '') !== '') ? item.clearable : true"
          :filterable="((item.filterable ?? '') !== '') ? item.filterable : false"
          :size="formSize"
          :placeholder="item.label"
          @change="handleSelectChange(item)">
          <el-option
            v-for="item in item.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"></el-option>
        </el-select>

        <!-- date-picker 日期 -->
        <el-date-picker
          v-else-if="item.type === FORM_TYPE_DATE"
          type="date"
          v-model="formData[item.prop]"
          :size="formSize"
          :placeholder="item.label"
        ></el-date-picker>

        <!-- cascader 联级下拉 -->
        <el-cascader
          v-else-if="item.type === FORM_TYPE_CASCADER"
          v-model="formData[item.prop]"
          :size="formSize"
          :placeholder="item.label"
          :options="item.options"
          :props="{ expandTrigger: item.expandTrigger || 'hover' }"
          :clearable="((item.clearable ?? '') !== '') ? item.clearable : true">
        </el-cascader>

        <!-- checkbox -->
        <el-checkbox
          v-else-if="item.type === FORM_TYPE_CHECKBOX"
          v-model="formData[item.prop]"
          @change="search">
          {{ item.label }}
        </el-checkbox>

        <!-- checkboxGroup -->
        <el-checkbox-group
          v-else-if="item.type === FORM_TYPE_CHECKBOX_GROUP"
          v-model="formData[item.prop]">
          <el-checkbox
            v-for="(checkbox, checkboxIndex) in item.options"
            :key="checkboxIndex"
            @change="search"
            :label="checkbox.value">
            {{ checkbox.label }}
          </el-checkbox>
        </el-checkbox-group>


    </el-col>
    <!-- 搜索按钮组 -->
    <el-col
      v-if="isShowSearchButton"
      :xs="xs"
      :sm="sm"
      :md='md'
      :lg='lg'
      :xl='xl'
      :xxl='xxl'
      :offset="btn_group_offset">
      <div class="actions" :class="{'action-align-right': actionsAlignRight}">
        <el-button type="primary" icon="el-icon-search" :size="formSize" @click="search">查询</el-button>
      </div>
    </el-col>
  </el-row>
</template>

<script>
/**
 * @param formList 表单控件列表
 * @param isShowSearchButton  控制是否显示【查询】按钮，默认显示
 * 
 * 
 * 下面是formList内容的可配置属性
 * @param type 控件的表单类型
 * @param label 控件的placeholder显示内容
 * @param prop 控件对应的formData属性
 * @param onChange 控件的change事件，目前仅select控件支持
 * @param options 控件对应的可选项
 * 
 * @method getFormData 获取表单数据
 * @method setFormData 设置表单数据
 * @method setOptions 设置控件的可选项列表
 * @method clearOptions 清空控件的可选项列表
 * @method search 搜索，接收参数：表单数据formData
 * @method reset 重置表单formData数据
 * 
 * 
 * @event search 搜索
 * @event [selfDefine]  可直接自定义
 */
export default {
  props: {
    formList: {
      type: Array,
      required: true
    },
    isShowSearchButton: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {

      isFormInit: false,
      formData: {},
      formSize: 'mini',
      

      FORM_TYPE_TEXT: 'text',
      FORM_TYPE_SELECT: 'select',
      FORM_TYPE_DATE: 'date',
      FORM_TYPE_CASCADER: 'cascader',
      FORM_TYPE_CHECKBOX: 'checkbox',
      FORM_TYPE_CHECKBOX_GROUP: 'checkboxGroup',

      xs: 24,
      sm: 12,
      md: 6,
      lg: 4,
      xl: 4,
      xxl: 4,
      checkboxCol: {
        xs: 24,
        sm: 12,
        md: 6,
        lg: 4,
        xl: 4,
        xxl: 4,

      },
      window_innerWidth: 0,
      btn_group_offset: 0,
      actionsAlignRight: false,
    }
  },
  watch: {
    window_innerWidth(w) {
        this.setBtnGroupOffset(w)
    }
  },
  methods: {
    // 表单数据初始化
    initForm() {
        let formData = {}
        this.formList.forEach(item => {
          
            const { type, prop } = item

            switch (type) {
              case this.FORM_TYPE_CHECKBOX:
                formData[prop] = false
                break
              case this.FORM_TYPE_CHECKBOX_GROUP:
                formData[prop] = []
                break
              default:
                formData[prop] = null
            }
            
        })

        this.formData = JSON.parse(JSON.stringify(formData))

        this.isFormInit = true
    },
    // 返回formData
    getFormData (opt) {
      const { dataType } = opt || {}
      if(dataType == 'FormData') {
        const formData = new FormData()
        this.formList.forEach(({ prop, type }) => {
          if(type == this.FORM_TYPE_FILE) {
            this.formData[prop].forEach(file => {
              formData.append(prop, file.raw)
            })
          } else {
            formData.append(prop, this.formData[prop])
          }
        })
        return formData
      } else {
        return this.formData
      }
    },
    // 设置formData
    setFormData (formData) {
      try {
        this.formList.forEach(({ prop, type }) => {
          if(typeof formData[prop] !== 'undefined') {
            if(type === this.FORM_TYPE_DATE) {
              this.formData[prop] = new Date(formData[prop])
            } else {
              this.formData[prop] = formData[prop]
            }
          }
        })
      } catch (err) {
        console.error(err)
      }
    },

    // 设置下拉列表的选项数据
    setOptions({ prop, options }) {
      const target = this.formList.find(item => item.prop === prop)
      if(target) {

        if(![this.FORM_TYPE_SELECT, this.FORM_TYPE_CASCADER].includes(target.type)) {
          console.warn(`${prop}的类型不正确,它没有options属性,${JSON.stringify(target)}`)
          return
        }
        if(options.length === 0) {
          target.options.splice(0, target.options.length)
        } else {
          target.options.splice(0, options.length)
          options.forEach(item => target.options.push(item))
        }
        

      } else {
        console.warn(`${prop}不存在${JSON.stringify(this.formList)}中`)
      }
    },
    // 清空下拉列表
    clearOptions(prop) {
      const target = this.formList.find(item => item.prop === prop)
      if(target) {

        if(![this.FORM_TYPE_SELECT, this.FORM_TYPE_CASCADER].includes(target.type)) {
          console.warn(`${prop}的类型不正确,它没有options属性,${JSON.stringify(target)}`)
          return
        }
        target.options.splice(0, target.options.length)
        
      } else {
        console.warn(`${prop}不存在${JSON.stringify(this.formList)}中`)
      }
    },

    // 下拉框change事件处理
    handleSelectChange(item) {
      if(item.onChange) {
        this.$emit(item.onChange)
      }
    },
    
    // 搜索
    search() {
      // this.setDateTimeFormat()
      // console.log(this.formData)
      this.$emit('search', this.formData)
    },
    // 重置
    reset() {
      Object.keys(this.formData).forEach(item => {
          this.formData[item] = null
      })
    },
    setBtnGroupOffset(w) {
      let [w_xs, w_sm, w_md, w_lg, w_xl] = [0, 768, 992, 1200, 1920]
      let form_amount = this.formList.length
      let offset = 0  // 需要偏移的数量
      let span = 0    // 剩余占位数量


      if(w >= w_xs && w < w_sm) {
        span = form_amount % (24 / this.xs)
        offset = span === 0 ? 24 - this.xs : 0
      } else if (w >= w_sm && w < w_md) {
        span = form_amount % (24 / this.sm)
        offset = span === 0 ? 24 - this.sm : 0
      } else if (w >= w_md && w < w_lg) {
        span = form_amount % (24 / this.md)
        offset = span === 0 ? 24 - this.md : 0
      } else if (w >= w_lg && w < w_xl) {
        span = form_amount % (24 / this.lg)
        offset = span === 0 ? 24 - this.lg : 0
      } else {
        span = form_amount % (24 / this.xl)
        offset = span === 0 ? 24 - this.xl : 0
      }

      this.btn_group_offset = offset
      this.actionsAlignRight = this.btn_group_offset !== 0

      // console.log('span', span)
      // console.log('offset', this.btn_group_offset)

    },
    
  },
  mounted() {
    this.initForm()
    this.setBtnGroupOffset(window.innerWidth)
    window.addEventListener('resize', () => {
        this.window_innerWidth = window.innerWidth
    })
  },
}
</script>

<style lang="less" scoped>
.base-search {
  // padding-top: 12px;
  .el-col {
    .el-input,
    .el-select,
    .el-date-editor,
    .el-cascader {
      width: 100%;
      margin-bottom: 12px;
    }
    .el-checkbox {
      margin-top: 4px;
    }
    .el-checkbox-group {
      min-height: 29px;
      display: flex;
      align-items: center;
    }
  }
  .el-button {
    margin-bottom: 12px;
  }
  .action-align-right {
    text-align: right;
  }
  @media screen and (max-width: 768px) {
    .el-button {
      width: 100%;
    }
  }
}

</style>